package com.ingesup.services;

import java.util.List;

import javax.mail.MessagingException;
import javax.mail.internet.AddressException;

import org.springframework.flex.remoting.RemotingDestination;
import org.springframework.stereotype.Service;

import com.ingesup.email.EmailSender;
import com.ingesup.entities.Contact;
import com.ingesup.entities.LettreType;
import com.ingesup.entities.ListeDeDiffusion;

@Service
@RemotingDestination("emailService")
public class EmailServiceImpl implements EmailService {

	public boolean envoyerEmail(List<?> listes, LettreType lettre) {
		if (listes.get(0) instanceof ListeDeDiffusion) {
			for (Object liste : listes) {
				for (Contact ct : ((ListeDeDiffusion)liste).getListeDeContacts()) {
					try {
						EmailSender.sendEmailSSL(lettre, ct);
					} catch (AddressException e) {
						e.printStackTrace();
						return false;
					} catch (MessagingException e) {
						e.printStackTrace();
						return false;
					}
				}		
			}
			return true;		
		}
		else if (listes.get(0) instanceof Contact) {
			try {
				for (Object contact : listes) {
					EmailSender.sendEmailSSL(lettre, (Contact)contact);
					return true;
				}
			} catch (AddressException e) {
				e.printStackTrace();
				return false;
			} catch (MessagingException e) {
				e.printStackTrace();
				return false;
			}
		}
		return false;
	}
}
